<?php

namespace App\Http\Controllers\Api\V1;

use App\B2BProject\Area;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\B2BProject\Custom\Business\Address;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Validator;

class MyAddressController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $list = \Auth::user()->address()->get();

        $data = [];

        foreach ($list as $address) {
            $data[] = [
                'id'                => $address->id,
                'name'              => $address->name,
                'province_id'       => $address->province_id,
                'city_id'           => $address->city_id,
                'county_id'         => $address->county_id,
                'code'              => $address->code,
                'province'          => Area::getName($address->province_id),
                'city'              => Area::getName($address->city_id),
                'county'            => Area::getName($address->county_id),
                'detail_area'       => $address->detail_area,
                'is_default'        => $address->default,
                'phone'             => $address->tel_phone,
                'mob_phone'         => $address->mob_phone,
                'publish_time'      => date('Y-m-d G:i:s', strtotime($address->created_at)),
                'publish_timestamp' => strtotime($address->created_at),
            ];
        }

        return success_return(['list' => $data]);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * 新的收货地址
     *
     * @param Request $request
     *
     * @return mixed
     *
     * @throws ModelNotFoundException
     * @throws \Exception
     */
    public function store(Request $request)
    {
        try {
            return \DB::transaction(function () use ($request) {
                $member = \Auth::user();

                $validator = Validator::make($request->all(), [
                    'name'        => 'required', // 姓名
                    'detail_area' => 'required', // 详细地址
                    'code'        => 'required', // 邮编
                    'tel_phone'   => 'required', //手机
                    'mob_phone'   => 'required', //座机
                    'province_id' => 'required|exists:areas,id,level,1', // 省份 ID
                    'city_id'     => 'required|exists:areas,id,level,2', // 城市 ID
                    'county_id'   => 'required|exists:areas,id,level,3', // 乡镇 ID
                ]);

                if ($validator->fails()) {
                    return error_return(900004, 403);
                }

                $data = $request->only([
                    'name',
                    'detail_area',
                    'code',
                    'tel_phone',
                    'mob_phone',
                    'province_id',
                    'city_id',
                    'county_id',
                ]);

                $address = Address::create($data);
                $member->address()->save($address);

                return success_return(['id' => $address->id]);
            });
        } catch (ModelNotFoundException $e) {
            throw $e;
        }
    }

    /**
     * Display the specified resource.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * 编辑我的收货信息
     * @param Request $request
     * @param $id
     * @return mixed
     * @throws ModelNotFoundException
     * @throws \Exception
     */
    public function update(Request $request, $id)
    {
        try {
            return \DB::transaction(function () use ($request, $id) {
                $member = \Auth::user();

                $validator = Validator::make($request->all(), [
                    'province_id' => 'exists:areas,id,level,1', // 省份 ID
                    'city_id'     => 'exists:areas,id,level,2', // 城市 ID
                    'county_id'   => 'exists:areas,id,level,3', // 乡镇 ID
                ]);

                if ($validator->fails()) {
                    return error_return(900004, 403);
                }

                $data = $request->only([
                    'name',
                    'detail_area',
                    'code',
                    'tel_phone',
                    'mob_phone',
                    'province_id',
                    'city_id',
                    'county_id',
                ]);

                $data['default'] = $request->input('is_default', 0);

                $address = $member->address()->whereId($id)->firstOrFail();

                if ($data['default'] == 1) {
                    $member->address()->where('default', true)->update(['default' => false]);
                }

                foreach ($data as $key => $value) {
                    if ($value || $key == 'default') {
                        $address->$key = $value;
                    }
                }

                $address->save();

                return success_return(null);
            });
        } catch (ModelNotFoundException $e) {
            throw($e);
        }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        Address::whereId($id)->delete();
        return success_return(null);
    }
}
